package com.gxa.order.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gxa.order.dao.ArtOrderDao;
import com.gxa.order.dao.MacOrderDao;
import com.gxa.order.dao.OrderCancelDao;
import com.gxa.order.dto.PageParam;
import com.gxa.order.param.LikeParam;
import com.gxa.order.param.PastParam;
import com.gxa.order.param.PastTicketParam;
import com.gxa.order.param.TicketParam;
import com.gxa.order.service.CheckService;
import com.gxa.order.service.OrderManageService;
import com.gxa.order.service.TicketService;
import com.gxa.order.service.UserService;
import dto.ResultDTO;
import entity.*;
import exception.SystemException;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import util.Response;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * @author htt
 * @create 2021-05-11
 * project overview
 */
@Service("orderManageService")
@Slf4j
public class OrderManageServiceImpl implements OrderManageService {


    @Resource
    private ArtOrderDao artOrderDao;

    @Resource
    private MacOrderDao macOrderDao;

    @Autowired
    private UserService userService;

    @Autowired
    private CheckService checkService;

    @Autowired
    private TicketService ticketService;

    @Resource
    private OrderCancelDao orderCancel;

    /**
     * 查询管理的订单
     * @param memberId
     * @param likeParam
     * @return
     */
    @Override
    public ResultDTO findAllOrder(Integer memberId, LikeParam likeParam) {
        if (memberId == null) {
            return Response.error(1001, "用户的id不能为空！");
        }
        ObjectMapper objectMapper = new ObjectMapper();
        //调用user的接口验证该用户是否存在
        // ***
        // user查询获取角色 and 角色的部门
        // ***
        ResultDTO member = userService.findAllById(memberId);
        if (member.getData() == null){
            throw new SystemException(1001, "该用户不存在！");
        }
        Member members = objectMapper.convertValue(member.getData(), Member.class);
        Integer roleId = members.getRoleId();
        if (roleId == null) {
            throw new SystemException(1001, "没有角色！");
        }
        //Integer roleId = 3;
        // 判断角色查询
        // 模拟
        // 查询到的列表
        Integer deptId = members.getDeptId();
        //Integer deptId = 1;
        PastTicketParam ticketParam = new PastTicketParam();
        List<TicketParam> list = new ArrayList<>();
        Integer count  = 0;
        if (roleId == 3){
            //查询人工订单
            ticketParam.setWaitCheckTicket(artOrderDao.findStatusOneAll());
            ticketParam.setOutTicket(artOrderDao.findStatusFiveAll());
            ticketParam.setWaitOutTicket(artOrderDao.findStatusFourAll());
            PageHelper.startPage(likeParam.getPageNum(), likeParam.getPageSize());
            List<ArtOrder> all1 = artOrderDao.findAll(likeParam);
            count = artOrderDao.artAllCount(likeParam);
            for (ArtOrder artOrder : all1) {
                TicketParam param = new TicketParam();
                param.setStartTime("请点击详情查看");
                param.setEndPlace("请点击详情查看");
                param.setFlightMsg("请点击详情查看");
                // 申请人的名字
                ResultDTO member3 = userService.findAllById(artOrder.getApplyId());
                if (member3.getData() == null){
                    throw new SystemException(1001, "该用户不存在！");
                }
                Member members3 = objectMapper.convertValue(member3.getData(), Member.class);
                param.setMemberName(members3.getMemberName());
                param.setOrderId(artOrder.getArtOrderId());
                param.setStatus(artOrder.getArtOrderStatus());
                param.setApplyMember(members3);
                // 如果是取消订单，查询取消原因
                if (artOrder.getArtOrderStatus() == 3) {
                    param.setCancelMsg(orderCancel.find(artOrder.getArtOrderId(), 0));
                }
                // 拒绝理由
                if (artOrder.getArtOrderStatus() == 2) {
                    ResultDTO resultDTO = checkService.checkOrder(artOrder.getArtOrderId(), 0);
                    if (resultDTO.getData() != null) {
                        ExaminePeople examinePeople = objectMapper.convertValue(resultDTO.getData(), ExaminePeople.class);
                        param.setRefuseMsg(examinePeople.getExaRefuseDesc());
                    }
                }
                param.setType(0);
                // 调用user的接口查询员工信息
                // ***
                ResultDTO member1 = userService.findAllById(artOrder.getMemberId());
                if (member1.getData() == null){
                    throw new SystemException(1001, "该用户不存在！");
                }
                Member members1 = objectMapper.convertValue(member1.getData(), Member.class);
                param.setMember(members1);
                param.setArtOrder(artOrder);
                // 调用审核接口查询审核人
                // ***
                ResultDTO resultDTO = checkService.exaArtOrderMember(artOrder.getArtOrderId());
                if (resultDTO.getData() != null){
                    String s = objectMapper.convertValue(resultDTO.getData(), String.class);
                    param.setCheckPerson(s);
                }
                list.add(param);
            }
        } else if (roleId == 2){
            /**
             * select DISTINCT mo.mac_order_id, mo.mac_order_code, mo.member_id, mo.apply_id, mo.mac_order_status, mo.is_urgency, mo.create_time, mo.update_time, mo.is_delete, o.fight_id, o.fight_price, o.order_fight_id from mac_order mo left join member m on mo.apply_id = m.member_id
             *         left join order_fight o on mo.mac_order_id = o.mac_order_id
             *         left join flight f on o.fight_id = f.flight_id
             *         where mo.is_delete = 0
             */
            ticketParam.setWaitCheckTicket(macOrderDao.findStatusOneAll(deptId));
            ticketParam.setOutTicket(macOrderDao.findStatusFiveAll(deptId));
            ticketParam.setWaitOutTicket(macOrderDao.findStatusFourAll(deptId));
            PageHelper.startPage(likeParam.getPageNum(), likeParam.getPageSize());
            List<MacOrder> allMac = macOrderDao.findSomeMac(likeParam, deptId);
            count =  macOrderDao.macSomeCount(deptId, likeParam);
            //调用飞机的接口
            //......
            // 模拟
            List<MacOrder> macOrders = allMac;
            for (MacOrder macOrder : macOrders) {
                TicketParam param = new TicketParam();
                param.setType(1);
                param.setStatus(macOrder.getMacOrderStatus());
                param.setOrderId(macOrder.getMacOrderId());
                ResultDTO member3 = userService.findAllById(macOrder.getApplyId());
                if (member3.getData() == null){
                    throw new SystemException(1001, "该用户不存在！");
                }
                Member members3 = objectMapper.convertValue(member3.getData(), Member.class);
                param.setMemberName(members3.getMemberName());
                param.setApplyMember(members3);
                // 拒绝理由
                if (macOrder.getMacOrderStatus() == 2) {
                    ResultDTO resultDTO = checkService.checkOrder(macOrder.getMacOrderId(), 1);
                    if (resultDTO.getData() != null) {
                        Examine examine = objectMapper.convertValue(resultDTO.getData(), Examine.class);
                        if (examine.getExamineFirstIsPoss() == 0) {
                            param.setRefuseMsg(examine.getExamineFirstRefuseDesc());
                        }else if (examine.getExamineSecondIsPoss() == 0) {
                            param.setRefuseMsg(examine.getExamineSecondRefuseDesc());
                        }
                    }
                }
                // 审核人
                ResultDTO resultDTO = checkService.exaMacOrderMember(macOrder.getMacOrderId());
                if (resultDTO.getData() != null){
                    String s = objectMapper.convertValue(resultDTO.getData(), String.class);
                    param.setCheckPerson(s);
                }
                // 取消原因
                if (macOrder.getMacOrderStatus() == 3) {
                    param.setCancelMsg(orderCancel.find(macOrder.getMacOrderId(), 1));
                }
                // 调用审核接口查询审核人
                // ***
                ResultDTO resultDTO1 = checkService.exaMacOrderMember(macOrder.getMacOrderId());
                if (resultDTO1.getData() != null){
                    String s = objectMapper.convertValue(resultDTO.getData(), String.class);
                    param.setCheckPerson(s);
                }
                if (macOrder.getOrderFights() == null || macOrder.getOrderFights().size() == 0) {
                    continue;
                }
                for (OrderFight orderFight : macOrder.getOrderFights()) {
                    if (orderFight == null){
                        break;
                    }
                    if (orderFight.getFlight() == null){
                        continue;
                    }
                    param.setEndPlace(orderFight.getFlight().getFlightEndAirport());
                    param.setStartTime(orderFight.getFlight().getFlightStartTime().toString());
                    param.setFlightMsg(orderFight.getFlight().getFlightCode());
                }
                param.setMacOrder(macOrder);
                // 调用user的接口查询员工信息
                // ***
                ResultDTO member2 = userService.findAllById(macOrder.getMemberId());
                if (member2.getData() == null){
                    throw new SystemException(1001, "该用户不存在！");
                }
                Member members2 = objectMapper.convertValue(member2.getData(), Member.class);
                param.setMember(members2);
                list.add(param);
            }
        }else if (roleId == 1){
            deptId = null;
            ticketParam.setWaitCheckTicket(macOrderDao.findStatusOneAll(deptId));
            ticketParam.setOutTicket(macOrderDao.findStatusFiveAll(deptId));
            ticketParam.setWaitOutTicket(macOrderDao.findStatusFourAll(deptId));
            PageHelper.startPage(likeParam.getPageNum(), likeParam.getPageSize());
            List<MacOrder> allMac = macOrderDao.findAllMac(likeParam);
            count = macOrderDao.macAllCount(likeParam);
            //调用飞机的接口
            //......
//_____________________________________________________________________________
            /*ResultDTO all = ticketService.findByFlightIdList(allMac);
            if (all == null) {
                throw new SystemException(1001, "没有机票！");
            }
            List<MacOrder> macOrders = (List<MacOrder>) all.getData();*/
//______________________________________________________________________________
            List<MacOrder> macOrders = allMac;
            for (MacOrder macOrder : macOrders) {
                TicketParam param = new TicketParam();
                param.setType(1);
                param.setStatus(macOrder.getMacOrderStatus());
                param.setOrderId(macOrder.getMacOrderId());
                ResultDTO member3 = userService.findAllById(macOrder.getApplyId());
                if (member3.getData() == null){
                    throw new SystemException(1001, "该用户不存在！");
                }
                Member members3 = objectMapper.convertValue(member3.getData(), Member.class);
                param.setMemberName(members3.getMemberName());
                param.setApplyMember(members3);
                // 取消原因
                if (macOrder.getMacOrderStatus() == 3) {
                    param.setCancelMsg(orderCancel.find(macOrder.getMacOrderId(), 1));
                }
                // 拒绝理由
                if (macOrder.getMacOrderStatus() == 2) {
                    ResultDTO resultDTO = checkService.checkOrder(macOrder.getMacOrderId(), 1);
                    if (resultDTO.getData() != null) {
                        Examine examine = objectMapper.convertValue(resultDTO.getData(), Examine.class);
                        if (examine.getExamineFirstIsPoss() == 0) {
                            param.setRefuseMsg(examine.getExamineFirstRefuseDesc());
                        }else if (examine.getExamineSecondIsPoss() == 0) {
                            param.setRefuseMsg(examine.getExamineSecondRefuseDesc());
                        }
                    }
                }
                // 审核人
                ResultDTO resultDTO = checkService.exaMacOrderMember(macOrder.getMacOrderId());
                if (resultDTO.getData() != null){
                    String s = objectMapper.convertValue(resultDTO.getData(), String.class);
                    param.setCheckPerson(s);
                }
                if (macOrder.getOrderFights() == null || macOrder.getOrderFights().size() == 0) {
                    continue;
                }
                // 飞机的信息
                for (OrderFight orderFight : macOrder.getOrderFights()) {
                    if (orderFight == null){
                        break;
                    }
                    if (orderFight.getFlight() == null){
                        continue;
                    }
                    param.setEndPlace(orderFight.getFlight().getFlightEndAirport());
                    param.setStartTime(orderFight.getFlight().getFlightStartTime().toString());
                    param.setFlightMsg(orderFight.getFlight().getFlightCode());
                }
                param.setMacOrder(macOrder);
                // 调用user的接口查询员工信息
                // ***
                ResultDTO member2 = userService.findAllById(macOrder.getMemberId());
                if (member2.getData() == null){
                    throw new SystemException(1001, "该用户不存在！");
                }
                Member members2 = objectMapper.convertValue(member2.getData(), Member.class);
                param.setMember(members2);
                list.add(param);
            }
        } else {
            return Response.error(100, "该用户没有该权限！");
        }
        PageInfo<TicketParam> pageInfo = new PageInfo<>(list);
        PastParam pastParam = new PastParam();
        pastParam.setPageInfo(pageInfo);
        pastParam.setParam(ticketParam);
        return Response.success(200, "成功！", count, pastParam);

    }

    /**
     * 人工（通过）
     * @param orderId
     * @return
     */
    @Override
    public ResultDTO updateStatusArtPass(Integer orderId) {
        if (orderId == null) {
            throw new SystemException(1001, "员工的订单id不能为空！");
        }
        ArtOrder order = artOrderDao.queryById(orderId);
        if (order.getArtOrderStatus() == 1){
            ArtOrder artOrder = new ArtOrder();
            artOrder.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            artOrder.setArtOrderStatus(4);
            artOrder.setArtOrderId(orderId);
            Integer integer = artOrderDao.updateStatus(artOrder);
            if (integer > 0){
                return Response.success(200, "修改成功！");
            }
            throw new SystemException(1001, "修改失败！");
        }
        throw new SystemException(1001, "只有待审核订单可以通过!");
    }

    /**
     * 人工（拒绝）
     * @param orderId
     * @return
     */
    @Override
    public ResultDTO updateStatusArtCancel(Integer orderId) {
        if (orderId == null) {
            throw new SystemException(1001, "员工的订单id不能为空！");
        }
        ArtOrder order = artOrderDao.queryById(orderId);
        if (order == null) {
            throw new SystemException(1001, "没有该订单");
        }
        ArtOrder artOrder = new ArtOrder();
        artOrder.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        artOrder.setArtOrderStatus(2);
        artOrder.setArtOrderId(orderId);
        Integer integer = artOrderDao.updateStatus(artOrder);
        if (integer > 0){
            return Response.success(200, "拒绝成功！");
        }
        throw new SystemException(1001, "拒绝失败！");
    }

    @Override
    public ResultDTO updateStatusArtOut(Integer orderId) {
        if (orderId == null) {
            throw new SystemException(1001, "员工的订单id不能为空！");
        }
        ArtOrder order = artOrderDao.queryById(orderId);
        if (order == null) {
            throw new SystemException(1001, "没有该订单");
        }
        ArtOrder artOrder = new ArtOrder();
        artOrder.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        artOrder.setArtOrderStatus(5);
        artOrder.setArtOrderId(orderId);
        Integer integer = artOrderDao.updateStatus(artOrder);
        if (integer > 0){
            return Response.success(200, "拒绝成功！");
        }
        throw new SystemException(1001, "拒绝失败！");
    }


    /**
     * 机械（通过）
     * @param orderId
     * @return
     */
    @Override
    public ResultDTO updateStatusMacPass(Integer orderId) {
        // 1
        MacOrder macOrder = macOrderDao.queryById(orderId);
        if (macOrder == null) {
            throw new SystemException(1001, "该订单不存在！");
        }
        MacOrder order1 = new MacOrder();
        order1.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        order1.setMacOrderStatus(4);
        order1.setMacOrderId(orderId);
        Integer integer = macOrderDao.updateStatus(order1);
        if (integer > 0){
            return Response.success(200, "修改成功！");
        }
        throw new SystemException(1001, "修改失败！");
    }

    /**
     * 机械（审核中）
     * @param orderId
     * @return
     */
    @Override
    public ResultDTO updateStatusMacIn(Integer orderId) {
        // 1
        MacOrder macOrder = macOrderDao.queryById(orderId);
        if (macOrder == null) {
            throw new SystemException(1001, "该订单不存在！");
        }
        MacOrder order1 = new MacOrder();
        order1.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        order1.setMacOrderStatus(0);
        order1.setMacOrderId(orderId);
        Integer integer = macOrderDao.updateStatus(order1);
        if (integer > 0){
            return Response.success(200, "修改成功！");
        }
        throw new SystemException(1001, "修改失败！");
    }

    @Override
    public ResultDTO updateStatusMacOut(Integer orderId) {
        MacOrder macOrder = macOrderDao.queryById(orderId);
        if (macOrder.getMacOrderStatus() == 4){
            MacOrder order1 = new MacOrder();
            order1.setUpdateTime(new Timestamp(System.currentTimeMillis()));
            order1.setMacOrderStatus(5);
            order1.setMacOrderId(orderId);
            Integer integer = macOrderDao.updateStatus(order1);
            if (integer > 0){
                return Response.success(200, "修改成功！");
            }
            throw new SystemException(1001, "修改失败！");
        }

        throw new SystemException(1001, "只有待审核订单可以通过!");
    }



    /**
     * 机械（拒绝）
     * @param orderId
     * @return
     */
    @Override
    public ResultDTO updateStatusMacCancel(Integer orderId) {
        MacOrder macOrder = macOrderDao.queryById(orderId);
        if (macOrder == null) {
            throw new SystemException(1001, "该订单不存在！");
        }
        MacOrder order1 = new MacOrder();
        order1.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        order1.setMacOrderStatus(2);
        order1.setMacOrderId(orderId);
        Integer integer = macOrderDao.updateStatus(order1);
        if (integer > 0){
            return Response.success(200, "修改成功！");
        }
        throw new SystemException(1001, "修改失败！");

    }



}
